package com.cn.steam.iam.config;

import com.cn.steam.foundation.common.web.config.jwt.CommonAccessDeniedHandler;
import com.cn.steam.foundation.common.web.config.jwt.CommonAuthenticationEntryPoint;
import com.cn.steam.iam.service.Oauth2UserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: zjm
 * @create: 2021-11-20 13:54
 **/
@Configuration
@Import({
        //重写401认证失败响应体
        CommonAuthenticationEntryPoint.class,
        //重写403权限不足响应体
        CommonAccessDeniedHandler.class
})

public class IamWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private CommonAuthenticationEntryPoint commonAuthenticationEntryPoint;

    @Autowired
    private CommonAccessDeniedHandler commonAccessDeniedHandler;

    @Autowired
    private Oauth2UserDetailService oauth2UserDetailService;

    /**
     * 配置登录管理器
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(oauth2UserDetailService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        List<String> permittAllResources = new ArrayList<>();
        //Swagger资源
        permittAllResources.addAll(Arrays.asList("/swagger-ui.html","/doc.html", "/v2/**", "/swagger-resources", "/swagger-resources/**", "/webjars/**","v3/**","favicon.ico"));  //"/test/**","/data/**","/oauth/**", "/login/**", "/logout/**",
        String[] resourceArray = permittAllResources.toArray(new String[]{});
        http.csrf().disable().formLogin().disable()
                .exceptionHandling()
                .authenticationEntryPoint(commonAuthenticationEntryPoint)
                .accessDeniedHandler(commonAccessDeniedHandler)
                .and()
                .authorizeRequests()
                .mvcMatchers(resourceArray).permitAll();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
